package com.ming.common.util;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ArrayUtil;
import com.ming.common.SelectOption;
import com.ming.common.SelectOptionItem;
import com.ming.common.anno.Describe;
import com.ming.common.anno.DescribeItem;

import java.beans.Transient;
import java.lang.reflect.Field;
import java.util.*;
import java.util.stream.Collectors;

public class ClassFieldUtil {

    public static SelectOption getFieldAnnoDescribe(Class clazz, String fieldName){
        return fieldAnnoHandler(clazz, CollUtil.newHashSet(fieldName)).getOrDefault(fieldName, new SelectOption());
    }

    public static Map<String, SelectOption> getFieldAnnoDescribe(Class clazz, Map<String,Object> map){
        boolean flag = map.containsKey("fieldNames");
        if(flag){
            Object fieldNameObj = map.get("fieldNames");
            if(fieldNameObj != null){
                String fieldNames = (String) fieldNameObj;
                String[] fieldArr = fieldNames.split(",");
                Set<String> fieldSet = Arrays.stream(fieldArr).collect(Collectors.toSet());
                return fieldAnnoHandler(clazz, fieldSet);
            }
        }
        return new HashMap<>();
    }


    public static Map<String, SelectOption> fieldAnnoHandler(Class clazz, Set<String> fieldSet){
        Map<String, SelectOption> map = new HashMap<>();
        Field[] fields = clazz.getDeclaredFields();
        for (Field field : fields) {

            if (field.isAnnotationPresent(Transient.class)) {
                continue;
            }
            String fieldName = field.getName();
            if(fieldSet.contains(fieldName)){
                SelectOption selectOption = new SelectOption();
                List<SelectOptionItem> optionsList = new ArrayList<>();
                boolean fieldAnnotationPresent = field.isAnnotationPresent(Describe.class);
                if(fieldAnnotationPresent){
                    String fieldType = field.getType().getSimpleName();
                    Describe describe = field.getAnnotation(Describe.class);
                    selectOption.setLabel(describe.value());
                    DescribeItem[] items = describe.items();
                    if(ArrayUtil.isNotEmpty(items)){
                        for (DescribeItem item : items){
                            if("Integer".equalsIgnoreCase(fieldType)){
                                optionsList.add(new SelectOptionItem(item.desc(),Integer.parseInt(item.value())));
                            }else{
                                optionsList.add(new SelectOptionItem(item.desc(),item.value()));
                            }
                        }
                    }
                }

                selectOption.setList(optionsList);
                map.put(fieldName, selectOption);
            }
        }
        return map;
    }
}
